package com.koron.order.linepatrol.uav.controller;

import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.EasyExcelUtils;
import com.koron.order.linepatrol.satellite.excel.LinePatrolSatelliteSSConverter;
import com.koron.order.linepatrol.uav.bean.VO.LineRiskPatrolUnvDetail;
import com.koron.order.linepatrol.uav.bean.dto.LineRiskPatrolUnvDetailDTO;
import com.koron.order.linepatrol.uav.bean.excel.LineRiskPatrolUnvDetailExcel;
import com.koron.order.linepatrol.uav.bean.query.LineRiskPatrolUnvDetailQuery;
import com.koron.order.linepatrol.uav.converter.LineRiskPatrolUnvConverter;
import com.koron.order.linepatrol.uav.excel.LineRiskPatrolUnvDetailListener;
import com.koron.order.linepatrol.uav.service.LineRiskPatrolUnvDetailService;
import com.koron.order.risk.base.excel.ErrorFillRowWriteHandler;
import com.koron.order.risk.feign.LineEquipmentFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * @ClassName: LinePatrolUnvDetailController
 * @Description:
 * @Date: 2023/2/11
 * @Author: 李一辰
 * @Version: 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/linePatrolUnvDetailController")
@Api(tags = "无人机风险巡视报告列表")
public class LineRiskPatrolUnvDetailController {

    /**
     * 服务对象
     */
    @Autowired
    private LineRiskPatrolUnvDetailService lineRiskPatrolUnvDetailService;
    @Autowired
    private LineEquipmentFeign equipmentFeign;
    @Autowired
    private LineRiskPatrolUnvConverter lineRiskPatrolUnvConverter;


    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    private EamUser getCurr() {
        return ThreadLocalContext.get();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping("getById")
    public Response<LineRiskPatrolUnvDetail> selectOne(@RequestParam String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), lineRiskPatrolUnvDetailService, "getById", LineRiskPatrolUnvDetail.class, id));
    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询(详细记录)")
    @GetMapping("selectDetailById")
    public Response<LineRiskPatrolUnvDetailDTO> selectDetailById(String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), lineRiskPatrolUnvDetailService, "selectDetailById", LineRiskPatrolUnvDetailDTO.class, id));
    }
    @ApiOperation(value = "分页查询")
    @GetMapping("page")
    public Response<PageInfo<LineRiskPatrolUnvDetail>> page(PageQuery pageQuery, LineRiskPatrolUnvDetailQuery query) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), lineRiskPatrolUnvDetailService, "page", PageInfo.class, pageQuery, query));
    }

    @ApiOperation(value = "保存")
    @PostMapping("save")
    public Response<LineRiskPatrolUnvDetail> save(@RequestBody(required = false) LineRiskPatrolUnvDetail lineRiskPatrolUnvDetail) {
        ADOConnection.runTask(getCurrDs(), lineRiskPatrolUnvDetailService, "save", Boolean.class, lineRiskPatrolUnvDetail);
        return Response.ok(lineRiskPatrolUnvDetail);
    }

    @ApiOperation(value = "更新")
    @PutMapping("update")
    public Response<LineRiskPatrolUnvDetail> update(@RequestBody LineRiskPatrolUnvDetail lineRiskPatrolUnvDetail) {
        ADOConnection.runTask(getCurrDs(), lineRiskPatrolUnvDetailService, "update", Boolean.class, lineRiskPatrolUnvDetail);
        return Response.ok(lineRiskPatrolUnvDetail);
    }

    @ApiOperation(value = "逻辑删除(隐藏)")
    @PostMapping("delete")
    public Response delete(@RequestParam String id) {
        ADOConnection.runTask(getCurrDs(), lineRiskPatrolUnvDetailService, "deleteById", Boolean.class, id);
        return Response.ok();
    }

    @SneakyThrows
    @ApiOperation(value = "下载无人机巡视模板")
    @GetMapping("/template")
    public void template1(HttpServletResponse response) {
        String path = "excel/patrol_unv_risk.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("无人机巡视风险报告导入单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());
    }

    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("/import")
    public Response importFile(@RequestParam("file") MultipartFile file, @RequestParam() String monitorId){
        LinePatrolSatelliteSSConverter stringConverter = new LinePatrolSatelliteSSConverter();
        LineRiskPatrolUnvDetailListener listener = new LineRiskPatrolUnvDetailListener(lineRiskPatrolUnvDetailService, lineRiskPatrolUnvConverter,equipmentFeign,monitorId);
        EasyExcel.read(file.getInputStream(), LineRiskPatrolUnvDetailExcel.class, listener)
                .registerConverter(stringConverter)
                .headRowNumber(1)
                .sheet(0)
                .doRead();
        if (listener.getExcelErrors().size() != 0) {
            String path = "excel/patrol_unv_risk_error.xlsx";
            ClassPathResource classPathResource = new ClassPathResource(path);
            // 输出错误文件
            String filename = CodeTools.getCodeNo("LineRiskPatrolDetail", 3);
            String tempPath = EasyExcelUtils.createTempFile(filename, "xlsx");
            log.warn("导入失败，错误文件在：{}", tempPath);
            EasyExcel.write(tempPath)
                    .withTemplate(classPathResource.getInputStream())
                    .head(LineRiskPatrolUnvDetailExcel.class)
                    .needHead(false)
                    .registerConverter(stringConverter)
                    .registerWriteHandler(new ErrorFillRowWriteHandler(listener.getExcelErrors()))
                    .sheet(0)
                    .doWrite(listener.getErrorRisk());
            return Response.ok("temp/" + filename + ".xlsx");
        }
        return Response.ok("导入成功", null);
    }
}
